package com.example.vip1.activity;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import com.example.vip1.R;
import com.example.vip1.jianzaozhe.Designer;
import com.example.vip1.jianzaozhe.Designer2;
import com.example.vip1.jianzaozhe.House;
import com.example.vip1.jianzaozhe.House3;
import com.example.vip1.utils.LogUtil;
import com.example.vip1.zerenlian.Task1;
import com.example.vip1.zerenlian.Task2;
import com.example.vip1.zerenlian.Task3;
import com.example.vip1.zerenlian2.ChainManager;
import com.example.vip1.zerenlian2.Task21;
import com.example.vip1.zerenlian2.Task22;
import com.example.vip1.zerenlian2.Task23;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.Util;

/**
 *  Okhttp3基本使用 https://www.jianshu.com/p/da4a806e599b
 *
 *  网络请求框架OkHttp3全解系列
 *  https://blog.csdn.net/hfy8971613/article/details/105923446/
 */
public class OkhttpActivityVP101 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        okhttpuser();

        testJianzaozhe();
//        zerenlian();
        zerenlian2();
    }

    private void zerenlian2() {
        ChainManager chainManager = new ChainManager();
        chainManager.addTask(new Task21());
        chainManager.addTask(new Task22());
        chainManager.addTask(new Task23());

        chainManager.doAction("ok",chainManager);
    }

    private void zerenlian() {
        Task1 task1 = new Task1(false);
        Task2 task2 = new Task2(false);
        Task3 task3 = new Task3(true);
        task1.addNext(task2);
        task2.addNext(task3);

        task1.action();
    }

    private void testJianzaozhe() {
        Designer designer = new Designer();
        designer.addHeight(100);
        designer.addWidth(100);
        designer.setColor("red");


        designer.addHeight(200);
        designer.addWidth(100);
        designer.setColor("red");

//        House house = designer.build();
        //流式
        House house = new Designer2().addHeight(200).addWidth(300).setColor("blue").build();
        LogUtil.i(house.toString());

        House3 house3 = new House3.Builder().addColor("blue").addHeight(300).addWidth(500).build();
    }

    private String url = "http://www.baidu.com";
    private void okhttpuser() {

        // okhttp 基于socket

        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();//建造者模式
        Request request = new Request.Builder().url(url).build();

        /*
             注意url开头

                public Builder url(String url) {
                  if (url == null) throw new NullPointerException("url == null");

                  // 如果url是ws:开头会被替换为http:
                  // Silently replace web socket URLs with HTTP URLs.
                  if (url.regionMatches(true, 0, "ws:", 0, 3)) {
                    url = "http:" + url.substring(3);

                     // 如果url是wss:开头会被替换为https:
                  } else if (url.regionMatches(true, 0, "wss:", 0, 4)) {
                    url = "https:" + url.substring(4);
                  }

                  HttpUrl parsed = HttpUrl.parse(url);
                  if (parsed == null) throw new IllegalArgumentException("unexpected url: " + url);
                  return url(parsed);
                }
        */


        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback(){

            @Override
            public void onFailure(Call call, IOException e) {
                LogUtil.i("请求 onFailure");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                LogUtil.i("请求 onResponse success");

            }
        });

        // Caused by: java.lang.IllegalStateException: Already Executed
        /*

            RealCall源码
            @Override public void enqueue(Callback responseCallback) {
                synchronized (this) {                                   // 防止同一个请求调用两次
                  if (executed) throw new IllegalStateException("Already Executed");
                  executed = true;
                }
                captureCallStackTrace();
                eventListener.callStart(this);
                client.dispatcher().enqueue(new AsyncCall(responseCallback));
              }
         */
        call.enqueue(new Callback() {//重复了
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                InputStream inputStream = response.body().byteStream();
                byte[] bytes = response.body().bytes();

            }
        });



        /*
        Dispatcher 源码

            synchronized void enqueue(AsyncCall call) {
                //当前运行的队列值小于64，并同时访问一个机器目标host请求小于5 直接加入到运行队列，否则加入到等待队列

                if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
                  runningAsyncCalls.add(call);
                  executorService().execute(call);
                } else {
                  readyAsyncCalls.add(call);
                }
              }

         */



        /*
        RealCall源码 里到 AsyncCall
        execute()方法
         Response response = getResponseWithInterceptorChain();
         */

        /*

            Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
    interceptors.addAll(client.interceptors());
    interceptors.add(retryAndFollowUpInterceptor);// RetryAndFollowUpInterceptor 重试，请求重定向 转发
    interceptors.add(new BridgeInterceptor(client.cookieJar())); // 桥拦截器  添加head、压缩、解压
    interceptors.add(new CacheInterceptor(client.internalCache()));// 缓存拦截器
    interceptors.add(new ConnectInterceptor(client));// 链接拦截器
    if (!forWebSocket) {
      interceptors.addAll(client.networkInterceptors());
    }
    interceptors.add(new CallServerInterceptor(forWebSocket));// 真正和服务器进行传输

    //  责任链模式
    Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
        originalRequest, this, eventListener, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());

    return chain.proceed(originalRequest);
  }

         */




       ExecutorService executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));


        /*
            ArrayBlockingQueue  有限界

            LinkedBlockingQueue 无界限

            为什么要选择 SynchronousQueue  要么等于0，要么等于1  可以说是没有容量的
         */
    }
}